/**
 * @description:
 *   在点击的控件下方展开一个提示框，vue组件
 *
 * @export {component} v-ctip
 * @param {string} content 提示框的内容，html 字符串或 dom 节点
 * @param {boolen} right 是否右对齐
 *
 * @author soulran(xr@ethercap.com)
 */

// v ctip (click tip) 点击弹出的 tooltip
var ctip = $.SlotVue.extend({
    props: ['content', 'right'],
    data: function(){
        return {
            $ctip: false,
            uid: Date.now().toString().slice(-6) + Math.random().toString().slice(2, 8)
        };
    },
    mounted: function(){
        var _this = this, $el = this.$el, right = !!this.right;
        $.dom.on($el, "click", function(e){
            // first time click
            if(!_this.$ctip) {
                _this.$ctip = $.dom.create('div', {class: 'ctip'});
                if(right)_this.$ctip.classList.add("ctip-right");
                if(typeof _this.content == 'function'){
                    _this.$ctip.appendChild(_this.content());
                } else if(_this.content.nodeType){
                    _this.$ctip.appendChild(_this.content);
                } else {
                    _this.$ctip.innerHTML = _this.content;
                }
                document.body.appendChild(_this.$ctip);
            }
            // common check
            if($.dom.css(_this.$ctip).display != 'block'){
                _this.$ctip.classList.add('active');
                var offset = $.dom.offset($el);
                var posData = {
                    top: offset.top + parseInt($.dom.css($el).height) + 6,
                    left: "auto",
                    right: "auto"
                };
                if(right) {
                    posData.right = document.body.offsetWidth - offset.left - parseInt(offset.width);
                } else {
                    posData.left = offset.left + (parseInt(offset.width) - parseInt($.dom.offset(_this.$ctip).width)) / 2;
                }
                _this.$ctip.style.top = posData.top + 'px';
                _this.$ctip.style.left = posData.left + 'px';
                _this.$ctip.style.right = posData.right + 'px';

                $.dom.on(document.body, "click", _this.bindFunction);
            } else {
                _this.$ctip.classList.remove('active');
                $.dom.off(document.body, "click", _this.bindFunction);
            }
        });
    },
    beforeDestroy: function(){
        if(this.$ctip)$.dom.remove(this.$ctip);
        $.dom.off(document.body, "click", this.bindFunction);
        this.$emit('content-destroy');
    },
    methods: {
        bindFunction: function(e){
            if($.dom.closest(e.target, '.ctip'))return;
            if(this.$el.contains(e.target))return;
            this.$ctip.classList.remove('active');
            $.dom.off(document.body, "click", this.bindFunction);
        }
    }
});

module.exports = ctip;
